package com.molyfun.parents.activity.setting;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.account.EditProfileActivity;
import com.molyfun.parents.activity.common.BaseChoosePicActivity;
import com.molyfun.parents.activity.common.listactivity.ListActivity;
import com.molyfun.parents.activity.common.listactivity.factory.ListActivityFactory;
import com.molyfun.parents.activity.myorder.MineOrderActivity;
import com.molyfun.parents.activity.organization.OrganizationActivity;
import com.molyfun.parents.activity.record.MineRecordActivity;
import com.molyfun.parents.fragment.dialog.EditProfileDialogFragment;
import com.molyfun.parents.im.MyConnectionListener;
import com.molyfun.parents.rest.bean.UserResponse;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.squareup.picasso.Picasso;
import com.tencent.imsdk.TIMManager;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MineActivity extends BaseChoosePicActivity implements View.OnClickListener {

    public static final int REQUEST_CODE_CHANGE_ORGANIZATION = 2001;

    @InjectView(R.id.base_title_left)
    ImageView mBack;
    @InjectView(R.id.child_info_layout)
    RelativeLayout mChildInfoLayout;
    @InjectView(R.id.record_info_layout)
    RelativeLayout mRecordInfoLayout;
    @InjectView(R.id.evaluate_layout)
    RelativeLayout mEvaluateLayout;
    @InjectView(R.id.plan_layout)
    RelativeLayout mPlanLayout;
    @InjectView(R.id.report_layout)
    RelativeLayout mReportLayout;
    @InjectView(R.id.order_layout)
    RelativeLayout mOrderLayout;
    @InjectView(R.id.setting_layout)
    RelativeLayout mSettingLayout;
    @InjectView(R.id.real_name_layout)
    RelativeLayout mRealNameLayout;
    @InjectView(R.id.bing_zfb_layout)
    RelativeLayout mBindZfbLayout;

    @InjectView(R.id.profile_user_name)
    TextView mUserName;
    @InjectView(R.id.profile_organization)
    TextView mOrganization;
    @InjectView(R.id.avator)
    CircleImageView mAvator;
    @InjectView(R.id.change_organization)
    TextView mChangeOrganization;
    @InjectView(R.id.student_name)
    TextView mStudentName;

    private MyConnectionListener myConnectionListener;

    public static void startActivity(Context context){
        Intent intent = new Intent();
        intent.setClass(context, MineActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine);

        ButterKnife.inject(this);

        getSupportActionBar().setTitle("");

        myConnectionListener = new MyConnectionListener(this);

        mChildInfoLayout.setOnClickListener(this);
        mRecordInfoLayout.setOnClickListener(this);
        mEvaluateLayout.setOnClickListener(this);
        mPlanLayout.setOnClickListener(this);
        mReportLayout.setOnClickListener(this);
        mOrderLayout.setOnClickListener(this);
        mSettingLayout.setOnClickListener(this);
        mBack.setOnClickListener(this);
        mRealNameLayout.setOnClickListener(this);
        mBindZfbLayout.setOnClickListener(this);

        addTIMConfig();

    }

    @Override
    protected void onPause() {
        super.onPause();
        initUserInfo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void addTIMConfig() {
        myConnectionListener = new MyConnectionListener(this);
        TIMManager.getInstance().getUserConfig().setUserStatusListener(myConnectionListener);
    }


    private void initUserInfo(){
        if (MFPApplication.getInstance().getUser() != null) {
            if (!TextUtils.isEmpty(MFPApplication.getInstance().getUser().getImgurl())) {
                Picasso.with(MineActivity.this)
                        .load(MFPApplication.getInstance().getUser().getImgurl())
                        .config(Bitmap.Config.RGB_565)
                        .placeholder(R.mipmap.ic_header_default)
                        .into(mAvator);
            } else {
                mAvator.setImageResource(R.mipmap.ic_header_default);
            }
//                    topCategotyViewHolder.mUserName.setText(MFPApplication.getInstance().getUser().getStudentname() + "(" + MFPApplication.getInstance().getUser().getStudentremarkname() + ")");
            mUserName.setText(MFPApplication.getInstance().getUser().getUsername());
            mStudentName.setText("(" + MFPApplication.getInstance().getUser().getStudentname() + ")");
            mUserName.setOnClickListener(this);
//                    topCategotyViewHolder.mUserAge.setText(TimeUtils.getAge(MFPApplication.getInstance().getUser().getStudentbirthdatetime()));
//                    if (TextUtils.isEmpty(MFPApplication.getInstance().getUser().getStudentsex()) || MFPApplication.getInstance().getUser().getStudentsex().equals("0")) {
//                        topCategotyViewHolder.mUserSex.setText("男");
//                    } else {
//                        topCategotyViewHolder.mUserSex.setText("女");
//                    }
//                    topCategotyViewHolder.mUserIntegral.setText("积分:" + MFPApplication.getInstance().getUser().getIntegral());
//            topCategotyViewHolder.mOrderName.setText("当前套餐:" + MFPApplication.getInstance().getUser().getLastestorderproductname());
            if (MFPApplication.getInstance().getUser().getDepartlist() != null && MFPApplication.getInstance().getUser().getDepartlist().size() > 0) {

//                            topCategotyViewHolder.mProfileOrganization.setText("所在机构:" + getSelectedDepartName(MFPApplication.getInstance().getUser().getDepartlist()));

                mStudentName.setVisibility(View.VISIBLE);
                getSelectedDepartName2(MFPApplication.getInstance().getUser().getDepartlist());


            }else{
                mChangeOrganization.setText("绑定学员");
                mOrganization.setVisibility(View.GONE);
                mStudentName.setVisibility(View.GONE);
            }

            mAvator.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    choosePic();
                }
            });
            mChangeOrganization.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    OrganizationActivity.startForResultActivity(MineActivity.this, REQUEST_CODE_CHANGE_ORGANIZATION);
                }
            });

        } else {
            mAvator.setImageResource(R.mipmap.ic_header_default);
        }
    }


    public void getSelectedDepartName2(List<UserResponse.DepartBean> departBeanList) {
        if (departBeanList != null && departBeanList.size() > 0) {
            mChangeOrganization.setText("切换");
            for (UserResponse.DepartBean departBean : departBeanList) {
                if (departBean.isSelected()) {

                    mOrganization.setVisibility(View.VISIBLE);
                    PreferencesStorageUtil.setDepartname(MineActivity.this ,departBean.getDepartname());
                    mOrganization.setText(departBean.getDepartname() + "(" + departBean.getOrgcode() + ")");
                }
            }
        } else {
//            mOrganization.setText("点击切换绑定孩子");
            mChangeOrganization.setText("绑定学员");
            mOrganization.setVisibility(View.GONE);
            return;
        }
        mChangeOrganization.setText("切换");
//        PreferencesStorageUtil.setDepartname(getContext() ,departBeanList.get(0).getDepartname());
//        mOrganization.setText(departBeanList.get(0).getDepartname() + "(" + departBeanList.get(0).getOrgcode()+ ")");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.child_info_layout:
                if(TextUtils.isEmpty(PreferencesStorageUtil.getStudentId(this))){
                    OrganizationActivity.startActivity(this);
                }else{
                    EditProfileActivity.startActivity(this);
                }
                break;
            case R.id.profile_user_name:
                new EditProfileDialogFragment.EditProfileDialogBuilder()
                        .setEditProfileCallback(new EditProfileDialogFragment.EditProfileCallback() {
                            @Override
                            public void onUpdateSuccess() {
                                initUserInfo();
                            }
                        })
                        .build(getSupportFragmentManager().beginTransaction());

                break;
            case R.id.record_info_layout:

                if(TextUtils.isEmpty(PreferencesStorageUtil.getStudentId(this))){
                    OrganizationActivity.startActivity(this);
                }else{
                    MineRecordActivity.startActivity(this);
                }
                break;
            case R.id.evaluate_layout:
                if(TextUtils.isEmpty(PreferencesStorageUtil.getStudentId(this))){
                    OrganizationActivity.startActivity(this);
                }else{
                    ListActivity.startActivity(this, ListActivityFactory.ActivityType.ACTIVITY_REPORT_EVALUATE);
                }
                break;
            case R.id.plan_layout:
                if(TextUtils.isEmpty(PreferencesStorageUtil.getStudentId(this))){
                    OrganizationActivity.startActivity(this);
                }else{
                    ListActivity.startActivity(this, ListActivityFactory.ActivityType.ACTIVITY_REPORT_PLAN);
                }
                break;
            case R.id.report_layout:
                if(TextUtils.isEmpty(PreferencesStorageUtil.getStudentId(this))){
                    OrganizationActivity.startActivity(this);
                }else{
                    ListActivity.startActivity(this, ListActivityFactory.ActivityType.ACTIVITY_REPORT_REPORT);
                }
                break;
            case R.id.order_layout:
                //NONE
                MineOrderActivity.startActivity(this);
                break;

            case R.id.real_name_layout:
                RealNameActivity.startActivity(this);
                break;
            case R.id.setting_layout:
                //NONE
                MineSettingActivity.startActivity(this);
                break;
            case R.id.bing_zfb_layout:
                BindAlipayActivity.startActivity(this);
                break;

            case R.id.base_title_left:
                finish();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initUserInfo();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Activity.RESULT_OK){
            switch (requestCode){
                case REQUEST_CODE_CHANGE_ORGANIZATION:
//                    SplashActivity.startActivity(getContext());
//                    getActivity().finish();

                    initUserInfo();

                    break;
            }
        }
    }

    @Override
    public String getAttachmentFolder() {
        return "header";
    }

    @Override
    public void onPictureUploadBegin(String path, String UploadPath) {

    }

    @Override
    public void onPictureUploadSuccess(String localPath, String smallUrl, String originalUrl) {
//更新资料
        showProgressDialog();
        Call<UserResponse> call = MFPApplication.getInstance().getRestClient().updateInfo(null, originalUrl);
        call.enqueue(new Callback<UserResponse>() {
            @Override
            public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                if (response.body() != null && response.body().getData() != null) {
                    MFPApplication.getInstance().setUser(response.body().getData());
                    PreferencesStorageUtil.setUserBean(MineActivity.this, GsonUtil.toJson(response.body().getData()));
                    Message uimessage = new Message();
                    uimessage.what = EventDispatcherEnum.UI_EVENT_CHANGE_USERINFO;
                    MFPApplication.getInstance().getEventDispatcher().sendMessage(uimessage);
                    dismissProgressDialog();
                }
            }

            @Override
            public void onFailure(Call<UserResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });
    }

    @Override
    public void onPictureUploadFailed(String path, String UploadPath) {

    }

    @Override
    public void onVideoUploadSuccess(String cover, String path) {

    }
}
